//
//  CarRecodViewController.m
//  STool
//
//  Created by banggo on 15/7/6.
//
//

#import "CarRecodViewController.h"
#import "UIViewController+Base.h"
#import "SCoreData.h"

#import "CarNewInfoCell.h"
#import "CarInfoCell.h"
#import "CarNewRecordCell.h"
#import "CarRecordCell.h"
#import "AddCarInfoCell.h"

#import "CarInfo.h"
#import "CarRecord.h"

#import "CarDataCalculate.h"
@interface CarRecodViewController ()

@end
static NSString *carNewInfoCell = @"CarNewInfoCell";
static CGFloat carNewInfoCellheight;

static NSString *carInfoCell = @"CarInfoCell";
static CGFloat carInfoCellheight;

static NSString *carNewRecordCell = @"CarNewRecordCell";
static CGFloat carNewRecordCellheight;

static NSString *carRecordCell = @"CarRecordCell";
static CGFloat carRecordCellheight;

static NSString *addCarInfoCell = @"AddCarInfoCell";
static CGFloat addCarInfoCellheight;

@implementation CarRecodViewController
{
    UIControl *centerControl;
    
    BOOL isCarList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.rightButton = [self setDefaultRightButton];
    [self.rightButton setTitle:@"新纪录" forState:UIControlStateNormal];
    [self.rightButton setTitle:@"取消" forState:UIControlStateSelected];
    [self.rightButton addTarget:self action:@selector(addNewRecord:) forControlEvents:UIControlEventTouchDown];
    
    isCarList = NO;
    /**
     *  获取数据源
     */
    [self setDataToAllArray];
    
    [self.tableViews registerNib:[UINib nibWithNibName:carNewInfoCell bundle:nil] forCellReuseIdentifier:carNewInfoCell];
    carNewInfoCellheight = [CarNewInfoCell getHeight];
    
    [self.tableViews registerNib:[UINib nibWithNibName:carInfoCell bundle:nil] forCellReuseIdentifier:carInfoCell];
    carInfoCellheight = [CarInfoCell getHeight];
    
    [self.tableViews registerNib:[UINib nibWithNibName:carNewRecordCell bundle:nil] forCellReuseIdentifier:carNewRecordCell];
    carNewRecordCellheight = [CarNewRecordCell getHeight];
    
    [self.tableViews registerNib:[UINib nibWithNibName:carRecordCell bundle:nil] forCellReuseIdentifier:carRecordCell];
    carRecordCellheight = [CarRecordCell getHeight];
    
    [self.tableViews registerNib:[UINib nibWithNibName:addCarInfoCell bundle:nil] forCellReuseIdentifier:addCarInfoCell];
    addCarInfoCellheight = [AddCarInfoCell getHeight];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)setDataToAllArray
{
    self.carId = [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVECARID"];
    
    [self getChooseCarData];
    [self getRecordDatas];
}

/**
 *  获取汽车详情列表
 */
- (void)getCarDatas
{
    SCoreData *coreData = [[SCoreData sharedInstance]setTableName:TABLENAME_CARINFO andDatabaseName:DBNAME];
    NSMutableArray *getDatas = [coreData selectData:10 andOffset:0 andCompositorKey:@"carId" ];
    if (getDatas) {
        if (!self.carArray) {
            self.carArray = [[NSMutableArray alloc]init];
        }
        [self.carArray removeAllObjects];
        for (CarInfo *model in getDatas) {
            CarModel *cm = [[CarModel alloc]init];
            cm.carCellType = CAR_Info;
            cm.dataDictionary = [CarDataCalculate getInfoDataWithCarInfo:model];
            cm.model = model;
            [self.carArray addObject:cm];
        }
        [self.dataArray removeAllObjects];
        self.dataArray = nil;
        self.dataArray = [[NSMutableArray alloc]initWithArray:self.carArray];
    }
}
/**
 *  获取油耗记录
 */
- (void)getRecordDatas
{
    SCoreData *coreData = [[SCoreData sharedInstance]setTableName:TABLENAME_CARRECORD andDatabaseName:DBNAME];
    NSMutableArray *getDatas = [coreData selectData:10 andOffset:0 andCompositorKey:@"recordTime" andKeyAndValue:@"carId",self.carId, nil];
    if (getDatas) {
        if (!self.recordArray) {
            self.recordArray = [[NSMutableArray alloc]init];
        }
        [self.recordArray removeAllObjects];
        for (CarRecord *model in getDatas) {
            CarModel *cm = [[CarModel alloc]init];
            CarModel *lastModel = [self.recordArray lastObject];
            cm.carCellType = CAR_Record;
            cm.dataDictionary = [CarDataCalculate getRecordDataWithCarRecord:model andLastCarRecord:lastModel.model];
            cm.model = model;
            [self.recordArray addObject:cm];
        }
        CarModel *addButton = [[CarModel alloc]init];
        addButton.carCellType = others;
        addButton.dataDictionary = [[NSMutableDictionary alloc]init];
        [self.recordArray addObject:addButton];
        [self.dataArray removeAllObjects];
        self.dataArray = nil;
        self.dataArray = [[NSMutableArray alloc]initWithArray:self.recordArray];
        [self.tableViews reloadData];
    }
}
/**
 *  获取单一汽车详情
 */
- (void)getChooseCarData
{
    NSString *bigTitle = @"行车油耗数据记录";
    NSString *littleTitle = @"无车辆数据记录";
    SCoreData *coreData = [[SCoreData sharedInstance]setTableName:TABLENAME_CARINFO andDatabaseName:DBNAME];
    NSMutableArray *getDatas;
    if (self.carId) {
        getDatas = [coreData selectData:10 andOffset:0 andCompositorKey:@"carId" andKeyAndValue:@"carId",self.carId, nil];

    }
    else
    {
        littleTitle = @"点击此处选择车辆数据";
    }
    if (getDatas ) {
        CarInfo *model = [getDatas objectAtIndex:0];
        if (model) {
            bigTitle = [NSString stringWithFormat:@"车型:%@",model.carType];
            littleTitle = [NSString stringWithFormat:@"平均规范油耗:%@",model.glCost];
        }
    }
    if (centerControl) {
        centerControl = nil;
        [centerControl removeFromSuperview];
    }
    centerControl = [self setMainTitle:bigTitle andTitle:littleTitle];
    [centerControl addTarget:self action:@selector(chooseCarType:) forControlEvents:UIControlEventTouchDown];
}


- (void)insertNewRecordWithTimestamp:(NSString*)timestamp;
{
    SCoreData *coreData = [[SCoreData sharedInstance]setTableName:TABLENAME_CARRECORD andDatabaseName:DBNAME];
    NSMutableArray *getDatas = [coreData selectData:10 andOffset:0 andCompositorKey:nil andKeyAndValue:@"recordTime",timestamp, nil];
    if (getDatas && [getDatas count]==1) {
        CarRecord *model = [getDatas objectAtIndex:0];
        CarModel *newRd = [[CarModel alloc]init];
        newRd.carCellType = CAR_Record;
        CarModel *lastModel = [self.dataArray objectAtIndex:0];
        newRd.dataDictionary = [CarDataCalculate getRecordDataWithCarRecord:model andLastCarRecord:lastModel.model];
        [self tableViewAddIndexZeroObject:newRd];
    }
}
- (void)tableViewAddIndexZeroObject:(CarModel*)obejct
{
    [self.dataArray insertObject:obejct atIndex:0];
    [self.tableViews insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
    [self.tableViews scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    self.rightButton.selected = YES;
}
- (void)tableViewRemoveObjectAtIndexZero
{
    [self.dataArray removeObjectAtIndex:0];
    [self.tableViews deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
    self.rightButton.selected = NO;
}
- (void)tableViewRemoveCellOfCarinfo;
{
    CarModel *gets = [self.dataArray lastObject];
    if (gets.carCellType == others) {
        [self.dataArray removeLastObject];
        [self.tableViews reloadData];
    }
}
#pragma mark - ButtonAction
- (void)addNewRecord:(UIButton*)sender
{
    /**
     *  控制添加车型和添加车辆纪录的完成取消按钮功能
     */
    if (sender.selected == NO) {
        [self tableViewRemoveCellOfCarinfo];
        CarModel *newRd = [[CarModel alloc]init];
        newRd.carCellType = CAR_NEW_Record;
        newRd.dataDictionary = [[NSMutableDictionary alloc]init];
        [self tableViewAddIndexZeroObject:newRd];
    }
    else
    {
        UITableViewCell *newCell = [self.tableViews cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        if (isCarList == YES) {
            isCarList = NO;
            CarNewInfoCell *cell = (CarNewInfoCell*)newCell;
            [cell cleanTextDatas];
        }
        else
        {
            CarNewRecordCell *cell = (CarNewRecordCell*)newCell;
            [cell cleanTextDatas];
        }
        sender.selected = NO;
        [self getRecordDatas];
    }
}
- (void)chooseCarType:(UIButton*)sender
{
    isCarList = YES;
    [self getCarDatas];
    [self.tableViews reloadData];
    /**
     *  右边上面按钮变成取消
     */
    self.rightButton.selected = YES;
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarModel *model = [self.dataArray objectAtIndex:indexPath.row];
    switch (model.carCellType ) {
        case CAR_NEW_Record:
        {
            CarNewRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:carNewRecordCell];
            cell.delegate = self;
            return cell;
            break;
        }
        case CAR_NEW_Info:
        {
            CarNewInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:carNewInfoCell];
            cell.delegate = self;
            return cell;
            break;
        }
        case CAR_Info:
        {
            CarInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:carInfoCell];
            cell.carInfoData = model.dataDictionary;
            return cell;
            break;
        }
        case CAR_Record:
        {
            CarRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:carRecordCell];
            cell.carRecordData = model.dataDictionary;
            return cell;
            break;
        }
        case others:
        {
            AddCarInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:addCarInfoCell];
            cell.delegate = self;
            return cell;
            break;
        }
        default:
            break;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarModel *model = [self.dataArray objectAtIndex:indexPath.row];
    switch (model.carCellType ) {
        case CAR_Record:
        {
            return carRecordCellheight;
            break;
        }
        case CAR_NEW_Record:
        {
            return carNewRecordCellheight;
            break;
        }
        case CAR_Info:
        {
            return carInfoCellheight;
            break;
        }
        case CAR_NEW_Info:
        {
            return carNewInfoCellheight;
            break;
        }
        case others:
        {
            return addCarInfoCellheight;
            break;
        }
        default:
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (isCarList == YES) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        CarInfoCell *carCell = (CarInfoCell*)cell;
        [[NSUserDefaults standardUserDefaults] setObject:[carCell.carInfoData objectForKey:@"carId"]forKey:@"SAVECARID"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        self.carId = [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVECARID"];
        [self getChooseCarData];
        [self getRecordDatas];
        self.rightButton.selected = NO;
    }
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.dataArray removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}
@end
@implementation CarModel

@end